﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.Configuration;

using Wicresoft.RDW.Model;

namespace Wicresoft.RDW.Utility
{
    public class SendMail : IDisposable
    {
        #region
        SmtpClient client = new SmtpClient();
        string _mailServer = ConfigurationManager.AppSettings["MailServer"].ToString();
        int _port = int.Parse(ConfigurationManager.AppSettings["Port"].ToString());
        bool _enableSSL = bool.Parse(ConfigurationManager.AppSettings["EnableSSL"].ToString());
        string _userName = ConfigurationManager.AppSettings["UserName"].ToString();
        string _password = ConfigurationManager.AppSettings["Pwd"].ToString();
        string _from = ConfigurationManager.AppSettings["From"].ToString();
        #endregion

        #region attribute
        public bool EnableSSL
        {
            get;
            set;
        }
        public string UserName
        {
            get;
            set;
        }
        public string Password
        {
            get;
            set;
        }
        public NetworkCredential Certificates
        {
            get
            {
                NetworkCredential credetial = new NetworkCredential(UserName, Password);
                return credetial;
            }
        }
        public string From
        {
            get;
            set;
        }
        public string ReplyTo
        {
            get;
            set;
        }
        public string Subject
        {
            get;
            set;
        }
        public string Body
        {
            get;
            set;
        }
        #endregion

        #region overload Method
        /// <summary>
        /// send mail to one people and cc one people
        /// </summary
        /// <param name="m">MailTemplate</param>
        /// <param name="tempName">template Name</param>
        /// <param name="to"></param>
        /// <param name="cc"></param>
        public SendMail(MailTemplate m, string tempName, string replaceContent, string to, string cc)
        {
            setContent(m, tempName, replaceContent);
            InitSmtpClient(_mailServer, Certificates);
            Send(to, cc);
        }
        /// <summary>
        ///send mail to many people and cc many people
        /// </summary>
        ///<param name="m">MailTemplate</param>
        /// <param name="tempName"></param>
        /// <param name="toList"></param>
        /// <param name="ccList"></param>
        public SendMail(MailTemplate m, string tempName, string replaceContent, List<string> toList, List<string> ccList)
        {
            setContent(m, tempName, replaceContent);
            Send(toList, ccList);
        }
        /// <summary>
        ///send mail to many people and cc one people
        /// </summary>
        ///<param name="m">MailTemplate</param>
        /// <param name="tempName"></param>
        /// <param name="toList"></param>
        /// <param name="ccList"></param>
        public SendMail(MailTemplate m, string tempName, string replaceContent, List<string> toList, string cc)
        {
            setContent(m, tempName, replaceContent);
            InitSmtpClient(_mailServer, Certificates);
            Send(toList, cc);
        }
        /// <summary>
        ///send mail to one people and cc may people
        /// </summary>
        ///<param name="m">MailTemplate</param>
        /// <param name="tempName"></param>
        /// <param name="toList"></param>
        /// <param name="ccList"></param>
        public SendMail(MailTemplate m, string tempName, string replaceContent, string to, List<string> ccList)
        {
            setContent(m, tempName, replaceContent);
            InitSmtpClient(_mailServer, Certificates);
            Send(to, ccList);
        }
        private void setContent(MailTemplate m, string tempName, string replaceContent)
        {
            try
            {
                From = _from;
                EnableSSL = _enableSSL;
                UserName = _userName;
                Password = _password;
                Subject = m.Subject;
                //Body = MailFormat.TemplateFormat(m.Template, replaceContent);
                string template = System.Text.RegularExpressions.Regex.Replace(m.Template, "<[^>]*>", "");//去掉所有html标签
                //template = template.Replace("{", " {").Replace("}", "} ");//在每个参数前加空格
                Body = MailFormat.TemplateFormat(template.Replace("&nbsp;", " ").Replace("&amp;", "&"), replaceContent);
                InitSmtpClient(_mailServer, Certificates);
            }
            catch (Exception ex)
            {
                Send("janeli@wicresoft.com", "", "Exception", ex.Message);
            }
        }
        //public MailUtil(string mailServer, int port, bool enableSSL, string userName, string pwd)
        //{
        //    EnableSSL = enableSSL;
        //    UserName = userName;
        //    Password = pwd;

        //    InitSmtpClient(mailServer, Certificates);
        //}

        /// <summary>
        /// Init smtp server by sharepoint
        /// </summary>
        /// <param name="host"></param>
        /// <param name="c"></param>
        protected void InitSmtpClient(string host, ICredentialsByHost c)
        {
            try
            {
                client.Host = host;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.EnableSsl = EnableSSL;
                client.UseDefaultCredentials = false;
                client.Credentials = c;
            }
            catch (Exception ex)
            {
                Logger.Log(ex.Message);
            }
        }
        #endregion

        #region send Methods
        private void Send(string to, string cc, string subject, string body)
        {
            Subject = subject;
            Body = body;
            List<string> toList = new List<string>();
            List<string> ccList = new List<string>();
            toList.Add(to);
            ccList.Add(cc);

            Send(toList, ccList);
        }

        //AD4\huifj updated on 2011/10/27
        private void Send(List<string> toList, List<string> ccList)
        {

            if ((toList == null || toList.Count == 0)
                && (ccList == null || ccList.Count == 0))
            {
                Logger.Log("No to mail person...");
                return;
            }
            try
            {
                MailMessage message = new MailMessage();
                message.From = new MailAddress(From);
                if (toList!=null && toList.Count != 0)
                {
                    foreach (string to in toList)
                    {
                        if (!string.IsNullOrEmpty(to))
                            message.To.Add(to);
                    }
                }
                if (!string.IsNullOrEmpty(From) || !string.IsNullOrEmpty(ReplyTo))
                    message.ReplyTo = new MailAddress(string.IsNullOrEmpty(ReplyTo) ? From : ReplyTo);
                foreach (string cc in ccList)
                {
                    if (!string.IsNullOrEmpty(cc))
                        message.CC.Add(Conver2MailAddress(cc));
                }
                message.Subject = Subject;
                message.Body = Body;

                if (!string.IsNullOrEmpty(client.Host))
                {
                    client.Send(message);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("",ex);
            }
        }
        private void Send(List<string> toList, string cc)
        {
            List<string> ccList = new List<string>();
            if (!string.IsNullOrEmpty(cc))
                toList.Add(cc);
            Send(toList, ccList);
        }
        private void Send(string to, List<string> ccList)
        {
            List<string> toList = new List<string>();
            toList.Add(to);
            Send(toList, ccList);
        }
        private void Send(string to, string cc)
        {
            List<string> toList = new List<string>();
            List<string> ccList = new List<string>();
            toList.Add(to);
            ccList.Add(cc);
            Send(toList, ccList);
        }
        private MailAddress Conver2MailAddress(string mailList)
        {
            return new MailAddress(mailList);

        }
        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            GC.Collect();
        }
        #endregion
    }
}
